import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:tiktokadult/assets_tool/images.dart';

class NumberKeyboard extends StatefulWidget {
  final Function(int index) keybordOnClick;
  const NumberKeyboard({super.key, required this.keybordOnClick});

  @override
  State<NumberKeyboard> createState() => _NumberKeyboardState();
}

class _NumberKeyboardState extends State<NumberKeyboard> {
  final spaceing = 6.0;

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Container(
        padding: EdgeInsets.all(spaceing),
        decoration: BoxDecoration(color: Color(0xffD8DADE)),
        child: GridView.builder(
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            mainAxisSpacing: spaceing,
            crossAxisSpacing: spaceing,
            childAspectRatio: 133 / 55,
          ),
          itemCount: 12,
          itemBuilder: (BuildContext context, int index) {
            if (index == 9) return SizedBox.shrink();

            return GestureDetector(onTap: () {
              widget.keybordOnClick(index);
            }, child: () {
              if (index == 11)
                return Container(
                  alignment: Alignment.center,
                  child: Image.asset(
                    'keyboard_delete.png'.mineImgPath,
                    width: 28,
                    height: 21,
                  ),
                );
              return Container(
                alignment: Alignment.center,
                child: Text(
                  index == 10 ? '0' : '${index + 1}',
                  style: TextStyle(color: Colors.black, fontSize: 28),
                ),
                decoration: BoxDecoration(
                    color: Colors.white,
                    border: Border(bottom: BorderSide(color: Color(0xff757575), width: 1)),
                    borderRadius: BorderRadius.circular(5)),
              );
            }());
          },
        ),
      ),
    );
  }
}

class PasswordWidget extends StatefulWidget {
  PasswordWidget({
    Key? key,
    this.itemWidth = 16,
    this.itemSpace = 23,
    this.maxLength = 6,
    this.controller,
    required this.completeInput,
  }) : super(key: key);

  final Function(String code) completeInput;

  final double itemWidth;

  final int maxLength;
  final double itemSpace;
  final TextEditingController? controller;

  @override
  State<PasswordWidget> createState() => _PasswordWidgetState();
}

class _PasswordWidgetState extends State<PasswordWidget> {
  FocusNode focusNode = FocusNode();
  late final TextEditingController controller = widget.controller ?? TextEditingController();

  @override
  initState() {
    super.initState();

    focusNode.requestFocus();
    controller.addListener(() {
      // print(controller.text);
      if (widget.controller?.text.length == widget.maxLength) {
        widget.completeInput(controller.text);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 16,
      child: LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          var size = Size(constraints.maxWidth, constraints.maxHeight);
          return CustomPaint(
            size: size,
            painter: CodeCustomPainter(widget.maxLength, size.width, size.height, focusNode, controller),
            child: TextField(
              //控制焦点
              focusNode: focusNode,
              controller: controller,
              //光标不显示
              showCursor: false,
              //光标颜色透明
              cursorColor: Colors.transparent,
              enableInteractiveSelection: false,
              //设置最大长度
              maxLength: widget.maxLength,
              //文字样式为透明
              style: const TextStyle(
                color: Colors.transparent,
              ),
              //只允许数据数字
              inputFormatters: [
                FilteringTextInputFormatter.digitsOnly,
              ],
              //弹出数字键盘
              keyboardType: TextInputType.number,
              //边框样式取消
              decoration: null,
            ),
          );
        },
      ),
    );
  }
}

class CodeCustomPainter extends CustomPainter {
  double width;
  double height;

  //焦点
  FocusNode focusNode;

  TextEditingController controller;

  //线路画笔
  late Paint linePaint;

  //文字画笔
  late TextPainter textPainter;

  //当前文字索引
  int currentIndex = 0;

  //左右间距值
  double space = 0;

  final int maxLength;

  CodeCustomPainter(
    this.maxLength,
    this.width,
    this.height,
    this.focusNode,
    this.controller,
  ) {
    linePaint = Paint()
      ..color = Colors.white
      ..isAntiAlias = true
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;

    textPainter = TextPainter(
      textAlign: TextAlign.center,
      textDirection: TextDirection.ltr,
    );
  }

  @override
  void paint(Canvas canvas, Size size) {
    //当前索引（待输入的光标位置）
    currentIndex = controller.text.length;

    height = height;

    //绘制样式

    _drawCircleCode(canvas, size);
  }

  void _drawCircleCode(Canvas canvas, Size size) {
    final marigin = (size.width - 16 * maxLength - 23 * (maxLength - 1)) / 2;
    double cx = marigin + 8 + 23;
    for (int i = 0; i < maxLength; ++i) {
      if (i <= currentIndex - 1) {
        canvas.drawCircle(
            Offset(cx, 0),
            8,
            linePaint
              ..color = Color(0xffDB361F)
              ..style = PaintingStyle.fill);
      } else {
        canvas.drawCircle(
            Offset(cx, 0),
            8,
            linePaint
              ..color = Colors.white
              ..style = PaintingStyle.stroke);
      }
      cx = cx + 23 + 8;
    }
    print('_drawCircleCode  ${currentIndex}  ${marigin}');
  }

  /*
   * 绘制验证码文字
   */
  void _drawContentCode(Canvas canvas, Size size) {
    textPainter.text = TextSpan(
      text: '',
      style: const TextStyle(color: Colors.white, fontSize: 24),
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
